package com.kim.useroauth.server.controller;

import com.kim.common.utilcom.utils.VerificationCodUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * 验证码获取Controller
 */
@Slf4j
@Controller
@RequestMapping("/app/v1/verificationCode/unAuthenticated")
public class VerificationCodeController {


    /**
     * 验证码{@value}
     */
    private static final String VERIFICATION_CODE_COMMON = "verification_code";

    /**
     * redis
     */
    private final RedisTemplate<String, Object> redisTemplate;

    public VerificationCodeController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 验证码获取
     * <p>
     * {@code key}唯一键为空时为首次获取验证码，刷新时需要携带第一次返回的key
     * 通过redis存储验证码
     * </p>
     *
     * @param key  唯一键
     * @param resp HttpServletResponse
     */
    @RequestMapping("getVerificationCodeImage")
    public void getAccessConfirmation(HttpServletResponse resp,
                                      @RequestParam(name = "key", required = false) String key) throws IOException {
        // 获取随机验证码
        String code = VerificationCodUtil.getRandomString();

        // 刷新唯一键
        if (StringUtils.isEmpty(key)) {
            // 唯一键
            key = UUID.randomUUID().toString().replace("-", "");
        }
        // 将UUID或者雪花算法等通过响应头传回客户端  // 建议使用UUID或者雪花算法等
        resp.setHeader("key", key);
        // 放入redis中存储
        redisTemplate.opsForHash().put(VERIFICATION_CODE_COMMON, key, code);
        log.info("verificationCode放入redis中存储 key -> {} , code -> {}", key, code);
        // 调过生成验证码图片的方法
        BufferedImage img = VerificationCodUtil.getImage(130, 50, code);
        // 设置resp的响应内容类型，前端将是blob
        resp.setContentType("image/jpeg");
        // 将图片通过输出流返回给客户端
        OutputStream out = resp.getOutputStream();
        ImageIO.write(img, "jpeg", out);
        out.close();
    }
}
